﻿namespace Point3DProgram
{
    using System;
    using System.IO;

    public static class PathStorage
    {
        private static readonly string fileName = "path.txt";

        public static void Save(Path path)
        {
            if (!File.Exists(fileName))
            {
                File.Create(fileName);
            }

            Save(path, fileName);
        }

        public static void Save(Path path, string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("File name can't be null or empty.");
            }
            else if (!File.Exists(fileName))
            {
                throw new FileNotFoundException("File not found.");
            }

            using (StreamWriter streamWriter = new StreamWriter(fileName))
            {
                foreach (var point in path.List)
                {
                    streamWriter.WriteLine(point);
                    streamWriter.Flush();
                }
            }
        }

        public static Path Load()
        {
            return Load(fileName);
        }

        public static Path Load(string fileName)
        {
            Path path = new Path();
            using (StreamReader streamReader = new StreamReader(fileName))
            {
                while (streamReader.Peek() >= 0)
                {
                    string line = streamReader.ReadLine();
                    string[] splittedLine = line.Split(new char[] { '(', ';', ')' }, StringSplitOptions.RemoveEmptyEntries);
                    int lineNumber;
                    if (!LineIsValid(splittedLine, out lineNumber))
                    {
                        throw new FormatException(string.Format("Invalid file format in line: {0}", lineNumber));
                    }

                    Point3D point3D = new Point3D(double.Parse(splittedLine[0]), double.Parse(splittedLine[1]), double.Parse(splittedLine[2]));
                    path.Add(point3D);
                }
            }

            return path;
        }

        private static bool LineIsValid(string[] splittedLine, out int errorLineNumber)
        {
            for (int i = 0; i < splittedLine.Length; i++)
            {
                double point;
                if (!double.TryParse(splittedLine[i], out point))
                {
                    errorLineNumber = i;
                    return false;
                }
            }

            errorLineNumber = -1;
            return true;
        }
    }
}
